/**
 * <h2>字符流操作器相关.</h2>
 * <pre>
 * <b>请使用 {@link fybug.nulll.pdstream.Source.StreamSource.Strings} 生成操作源</b>
 * 操作器均有 <b>常规操作方法</b> 用于操作 <b>稳定流</b>
 * 在 <b>连续操作</b> 中可以使用接口对读取的片段进行处理
 * </pre>
 *
 * @author fybug
 * @version 0.0.8
 * @since JDK 1.8
 */
package fybug.nulll.pdstream.WR.Stream;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;

import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;

import fybug.nulll.pdstream.Interface.UpdateSize;
import fybug.nulll.pdstream.WR.Err.CharStreamErr;
/** <h2>缓冲区操作.</h2> */
final
class Help {
    /** <p>更新字符缓冲区大小.</p> */
    @NotNull
    static
    CharBuffer upBufferSize(@Nullable final UpdateSize see, @NotNull CharBuffer charBuffer,
            final int readSize)
    {
        if (see != null) {
            synchronized ( charBuffer ){
                // 更新缓冲区大小
                int up = see.updataSize(readSize);
                if (up == readSize)
                    /* 缓冲区大小不变 */
                    charBuffer.clear();
                else {
                    if (up <= 0)
                        up = 0;
                    charBuffer = CharBuffer.allocate(up);
                }
            }
        }
        return charBuffer;
    }

    static
    int[] getLine(@NotNull final StringBuilder stringBuffer, final int streamMark,
            final Reader... r) throws CharStreamErr
    {
        @NotNull Reader re = null; // 减少寻址次数
        int i; // 单次读取返回
        int mark = 0, ma = 0;
        try {
            stream:
            for ( int i1 = streamMark; i1 < r.length; ){
                /* 读取所有流 */
                mark = i1;
                re = r[i1];
                while( (i = re.read()) != -1 ){
                    // 读取一个字符并放入缓存区
                    if (i == '\n') {
                        ma = 1;
                        break stream;
                    }
                    stringBuffer.append((char) i);
                }
                i1++;
                if (stringBuffer.length() != 0)
                    break;
            }
        } catch ( IOException e ) {
            throw new CharStreamErr(e.getMessage(), re, null);
        }
        return new int[]{mark, ma};
    }
}